/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*function loadSuccessful(state, recordArray, options)
{
    if(recordArray.length!= 0 && recordArray[0].data["locationType"]=="")
    {
        Ext.MessageBox.alert('Alert', 'Please plot a Point, Line or Area on Arcmap using GFTK Report Position Tools first.');
    }
    else
    {
        var locType = recordArray[0].data["locationType"];
        var radio = Ext.ComponentMgr.get(_globalLocTypeID);
        if(locType=="Point")
        {radio.items.items[0].setValue(true);}
        else if(locType=="Line")
        {radio.items.items[1].setValue(true);}
        else if(locType=="Area")
        {radio.items.items[2].setValue(true);}
        else
        {radio.items.items[0].setValue(false);radio.items.items[1].setValue(false);radio.items.items[2].setValue(false);}
        
        var locPts = recordArray[0].data["locationPoints"];
        var ds = Ext.ComponentMgr.get(_globalGridID).getStore();
        ds.loadData(locPts);
    }
}*/

function loadFailed(proxy, options, response, error)
{
    var object = Ext.util.JSON.decode(response.responseText);
    var errorMessage = response.responseText;
    Ext.MessageBox.alert('LoadFailed', error);
}

function locationPickerPanel(locationNameID, locationTypeID, latID, longID, gridID, locButID, addButID, delButID, anchorPercent, inHeight)
{
    // store ==============================================
    var locationStore = new Ext.data.Store
    ({
        autoDestroy: true,
        //url: 'LocationPickerServlet',
        url: 'locationPicker.htm?action=getUserPicked',
        reader: new Ext.data.JsonReader({
            root: 'data',
            fields: 
            [
                {name: 'locationType', type: 'string'},
                {name: 'locationPoints'}
            ]
        }),
        listeners: {
            'load': function(){
                locationStore.each
                (
                    function(recordObj)
                    {
                        var locType = recordObj.data["locationType"];
                        var locPts = recordObj.data["locationPoints"];
                        
                        if(locType == "" || locPts.length == 0)
                        {
                            Ext.MessageBox.alert('Alert', 'Please plot a Point, Line or Area on Arcmap using GFTK Report Position Tools first.');
                        }
                        else
                        {
                            var radio = _locationType;
                            if(locType=="Point")
                            {radio.items.items[0].setValue(true);}
                            else if(locType=="Line")
                            {radio.items.items[1].setValue(true);}
                            else if(locType=="Area")
                            {radio.items.items[2].setValue(true);}
                            else
                            {radio.items.items[0].setValue(false);radio.items.items[1].setValue(false);radio.items.items[2].setValue(false);}

                            var ds = _grid.getStore();
                            ds.loadData(locPts);
                        }
                    }
                )
            }
        }
    });
    //locationStore.on('load', loadSuccessful);
    locationStore.on('loadException', loadFailed);
    
    var pointsStore = new Ext.data.Store
    ({
        reader: new Ext.data.JsonReader({
            fields: 
            [
                {name: 'locationId', type: 'double'},
                {name: 'lat', type: 'double'},
                {name: 'long_', type: 'double'}
            ]
        })
    })
    pointsStore.on('loadException', loadFailed);
    
    // record model ============================================================
    var pointStore_row = Ext.data.Record.create
    ([	{name: 'lat',type: 'double',allowBlank: false},
	{name: 'long_',type: 'double',allowBlank: false}
    ]);
    
    // fields =============================================
    var _locationName = new Ext.form.TextField
    ({
        id: locationNameID,
        fieldLabel: '<span class=x-form-item-label-mandatory>* </span>Location Name',
        name: locationNameID,
        anchor: '95%'
        //width: 155,
        //allowBlank: false
    })
    
    var _locationType = new Ext.form.RadioGroup
    ({id: locationTypeID,
            width: 200,
            fieldLabel: '<span class=x-form-item-label-mandatory>* </span>Location Type',
            items:[
                {boxLabel: 'Point', name: locationTypeID, inputValue: "Point"},
                {boxLabel: 'Line', name: locationTypeID, inputValue: "Line"},
                {boxLabel: 'Area', name: locationTypeID, inputValue: "Area"}
            ]
    });
    
    var lat_edit = new Ext.form.TextField
    ({
        //width: 155,
        id: latID,
        allowBlank: false
    })

    var long_edit = new Ext.form.TextField
    ({
        //width: 155,
        id: longID,
        allowBlank: false
    })
    
    // grid ================================================
    var sm = new Ext.grid.RowSelectionModel
    ({
        singleSelect:false
    });
	
    var cm = new Ext.grid.ColumnModel({
        defaults: {
            sortable: false
        },
        columns: [{
            id: 'lat',
            header: '<span class=x-form-item-label-mandatory>* </span>Lat',
            dataIndex: 'lat', 
            editor: lat_edit
        },{
            id: 'long_',
            header: '<span class=x-form-item-label-mandatory>* </span>Long',
            dataIndex: 'long_', 
            editor: long_edit
        }]
    });
    
    var _grid = new Ext.grid.EditorGridPanel({
        id: gridID,
        height: inHeight,
        viewConfig: {
            forceFit: true
        },
        store: pointsStore,
        autoExpandColumn : 1,
        clicksToEdit: 1,
        //enableColumnMove: false, // to prevent invalidating the wrong column
        cm: cm,
        sm: sm,
        tbar: [{
            id: locButID,
            icon: 'images/arcmap.gif',
            text: 'Pick Location',
            handler: function(){
                locationStore.load();
            }
        },'-',{
            id: addButID,
            icon: 'images/add.gif',
            text: 'Add Point',
            handler: function()
            {
                _grid.stopEditing();
                _grid.getStore().insert
                (	_grid.getStore().getCount(), // insert into last record
                    new pointStore_row({
                        lat: '',
                        long_: ''
                    })
                    //	'assetId','weaponTypeId','weaponType', 'weaponSubTypeId', 'weaponSubType', 'quantity'
                    );
                _grid.getView().refresh();
                _grid.getSelectionModel().selectRow(_grid.getStore().getCount()-1);
                _grid.startEditing(_grid.getStore().getCount()-1,0);
            }
        },'-',{
            id: delButID,
            icon: 'images/delete.gif',
            text: 'Remove Point',
            handler: function()
            {
                var gridSelectionModel = _grid.getSelectionModel();
                var selected = gridSelectionModel.getSelections();
                if(selected.length > 0) 
                {
                    for(var i = 0, r; r = selected[i]; i++) 
                    {
                        pointsStore.remove(r); 
                    }
                }
            }
        }]
    });
    
    var locationFieldSet = new Ext.form.FieldSet({
        frame:true,
        //fieldLabel: 'Event Location',
	anchor: anchorPercent,
        //width: 300,
	padding: '8 0 0 0',
        defaults: {
            //allowBlank: false,
            selectOnFocus: true
            //,msgTarget: 'side'
        },
        items: [_locationName, _locationType, _grid]
    });

    return locationFieldSet;	
}


function validateLocation(locationNameID, locationTypeID, gridID)
{
    var errorArr = [];
	
    var grid = Ext.ComponentMgr.get(gridID);
    var locationType = Ext.ComponentMgr.get(locationTypeID);
	
    // Validate Location Name =====
    if(!Ext.ComponentMgr.get(locationNameID).getValue())
    {
        Ext.ComponentMgr.get(locationNameID).markInvalid("Please enter a Location Name");
    }
	
    // Validate Location Type =====
    if(!locationType.getValue())
    {
        locationType.markInvalid("Please select a Location Type");
    }
    else
    {
        // validate Point, Line, Area ====
        if(locationType.getValue().getGroupValue()=='Point' && grid.store.getCount()!=1)
        {
            errorArr.push('- Please define only 1 lat/long point for location of "Point" type');
        }
        else if(locationType.getValue().getGroupValue()=='Line' && grid.store.getCount()<2)
        {
            errorArr.push('- Please define at least 2 lat/long points for location of "Line" type');
        }
        else if(locationType.getValue().getGroupValue()=='Area' && grid.store.getCount()<3)
        {
            errorArr.push('- Please define at least 3 lat/long points for location of "Area" type');
        } 
		
        // validate lat/long records =====
        var locErrAdded=false;
        var locErrFound=false;
        for(i=0; i < grid.store.getCount(); i++)
        {
            var lat = grid.store.data.items[i].data["lat"];
            var long_ = grid.store.data.items[i].data["long_"];
			
            var cellLat = grid.getView().getCell(i,grid.getColumnModel().findColumnIndex('lat'));
            if(!lat || !(lat >= -90 && lat <= 90))
            {
                if(cellLat.className.indexOf(' x-form-invalid')==-1)
                {
                    cellLat.className += ' x-form-invalid';
                }
                locErrFound = true;
            }
            var cellLong = grid.getView().getCell(i,grid.getColumnModel().findColumnIndex('long_'));
            if(!long_ || !(long_ >= -180 && long_ <= 180))
            {
                if(cellLong.className.indexOf(' x-form-invalid')==-1)
                {
                    cellLong.className += ' x-form-invalid';
                }
                locErrFound = true;
            }
            
            /*if((!lat || !long_ || !(lat >= -90 && lat <= 90) || !(long_ >= -180 && long_ <= 180)) && !locErrAdded)
            {
                errorArr.push('- Please enter valid lat/long record(s)');
                //break;
                locErrAdded=true;
            }*/
        }
        
        if(locErrFound)
        {
            errorArr.push('- Please enter valid lat/long record(s)');
        }
    }
    return errorArr;
}